package com.bm.console.business.impl;

import com.alibaba.fastjson.serializer.CharsetCodec;
import com.bm.console.business.WeatherService;
import com.bm.console.pojo.WebCityItem;
import com.bm.console.pojo.WebWeather;
import com.bm.console.pojo.mapper.WebCityMapper;
import com.bm.console.pojo.mapper.WebWeatherMapper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.CharEncoding;
import org.apache.commons.lang.CharSet;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Consts;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

import static java.lang.System.out;

/**
 * Created by chen365 on 2018/04/12.
 */
@Service
public class WeatherServiceImpl implements WeatherService {

    @Autowired
    private WebWeatherMapper webWeatherMapper;

    @Autowired
    private WebCityMapper webCityMapper;

    public void download(String weatherId) {
        //参数字符串，如果拼接在请求链接之后，需要对中文进行 URLEncode   字符集 UTF-8
        String param = "key=225e055bd481480eaad576ac51231132&location=" + weatherId;
        StringBuilder sb = new StringBuilder();
        InputStream is = null;
        BufferedReader br = null;
        try {
            //接口地址
            String url = "https://free-api.heweather.com/s6/weather/forecast?parameters";
            URL uri = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) uri.openConnection();
            connection.setRequestMethod("POST");
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(10000);
            connection.setRequestProperty("accept", "*/*");
            //发送参数
            connection.setDoOutput(true);
            PrintWriter out = new PrintWriter(connection.getOutputStream());
            //out.print(URLEncoder.encode(param, CharEncoding.UTF_8));
            out.print(param);
            out.flush();
            //接收结果
            is = connection.getInputStream();
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String line;
            //缓冲逐行读取
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            out.println(sb.toString());
            System.err.println(sb.toString());
            JSONObject json = JSONObject.fromObject(sb.toString());
            WebWeather weather = new WebWeather();

            JSONObject HeWeather6 = json.getJSONArray("HeWeather6").getJSONObject(0);
            System.err.println(HeWeather6);

            JSONObject basic = HeWeather6.getJSONObject("basic");
            System.err.println(basic);

            JSONObject update = HeWeather6.getJSONObject("update");
            System.err.println(update);

            JSONObject daily_forecast = HeWeather6.getJSONArray("daily_forecast").getJSONObject(0);
            System.err.println(daily_forecast);

//            {"cid":"US4930956","location":"波士顿","admin_area":"","cnty":"美国",
//              "lat":"42.35842896","lon":"-71.05976868","tz":"-5.00"}
            if (basic.get("cid") != null)
                weather.setCid(basic.get("cid").toString());
            if (basic.get("location") != null)
                weather.setLocation(basic.get("location").toString());
            if (basic.get("admin_area") != null)
                weather.setAdminArea(basic.get("admin_area").toString());
            if (basic.get("cnty") != null)
                weather.setCnty(basic.get("cnty").toString());
            if (basic.get("lat") != null)
                weather.setLat(basic.get("lat").toString());
            if (basic.get("lon") != null)
                weather.setLon(basic.get("lon").toString());
            if (basic.get("tz") != null)
                weather.setTz(basic.get("tz").toString());

//            {"loc":"2018-04-12 02:46","utc":"2018-04-12 07:46"}
            if (update.get("loc") != null)
                weather.setLoc(update.get("loc").toString());
            if (update.get("utc") != null)
                weather.setUtc(update.get("utc").toString());
//{"cond_code_d":"309","cond_code_n":"309","cond_txt_d":"毛毛雨/细雨","cond_txt_n":"毛毛雨/细雨",
// "date":"2018-04-12","hum":"70","mr":"04:42","ms":"15:48","pcpn":"0.1","pop":"27","pres":"1017","sr":"06:08",
// "ss":"19:23","tmp_max":"11","tmp_min":"8","uv_index":"4","vis":"17","wind_deg":"264","wind_dir":"西风",
// "wind_sc":"1-2","wind_spd":"0"}
            if (daily_forecast.get("cond_code_d") != null)
                weather.setCondCodeD(daily_forecast.get("cond_code_d").toString());
            if (daily_forecast.get("cond_code_n") != null)
                weather.setCondCodeN(daily_forecast.get("cond_code_n").toString());
            if (daily_forecast.get("cond_txt_d") != null)
                weather.setCondTxtD(daily_forecast.get("cond_txt_d").toString());
            if (daily_forecast.get("cond_txt_n") != null)
                weather.setCondTxtN(daily_forecast.get("cond_txt_n").toString());
            if (daily_forecast.get("date") != null)
                weather.setDate(daily_forecast.get("date").toString());
            if (daily_forecast.get("hum") != null)
                weather.setHum(daily_forecast.get("hum").toString());
            if (daily_forecast.get("mr") != null)
                weather.setMr(daily_forecast.get("mr").toString());
            if (daily_forecast.get("ms") != null)
                weather.setMs(daily_forecast.get("ms").toString());
            if (daily_forecast.get("pcpn") != null)
                weather.setPcpn(daily_forecast.get("pcpn").toString());
            if (daily_forecast.get("pop") != null)
                weather.setPop(daily_forecast.get("pop").toString());
            if (daily_forecast.get("pres") != null)
                weather.setPres(daily_forecast.get("pres").toString());
            if (daily_forecast.get("sr") != null)
                weather.setSr(daily_forecast.get("sr").toString());
            if (daily_forecast.get("ss") != null)
                weather.setSs(daily_forecast.get("ss").toString());
            if (daily_forecast.get("tmp_max") != null)
                weather.setTmpMax(daily_forecast.get("tmp_max").toString());
            if (daily_forecast.get("tmp_min") != null)
                weather.setTmpMin(daily_forecast.get("tmp_min").toString());
            if (daily_forecast.get("uv_index") != null)
                weather.setUvIndex(daily_forecast.get("uv_index").toString());
            if (daily_forecast.get("vis") != null)
                weather.setVis(daily_forecast.get("vis").toString());
            if (daily_forecast.get("wind_deg") != null)
                weather.setWindDeg(daily_forecast.get("wind_deg").toString());
            if (daily_forecast.get("wind_dir") != null)
                weather.setWindDir(daily_forecast.get("wind_dir").toString());
            if (daily_forecast.get("wind_sc") != null)
                weather.setWindSc(daily_forecast.get("wind_sc").toString());
            if (daily_forecast.get("wind_spd") != null)
                weather.setWindSpd(daily_forecast.get("wind_spd").toString());
            weather.setCreateTime(new Date());
            weather.setStatus(true);
            System.err.println(weather);

            webWeatherMapper.insert(weather);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭流
            try {
                if (is != null) {
                    is.close();
                }
                if (br != null) {
                    br.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e2) {
            }
        }
    }

    @Override
    public void save() {
        List<WebCityItem> list = webCityMapper.selectAll();
        if (list.size() > 0) {
            for (WebCityItem item : list) {
                String weatherId = item.getWeatherId();
                if (!StringUtils.isEmpty(weatherId)) {
                    download(weatherId);
                }
            }
        }
    }
}
